import { defineStore } from 'pinia';
import { logoutUser, getTongYiSystemUrl } from '@/api/login';
import { getCategory } from '@/api/goods';
import storage from '@/utils/storage';
import { UserState } from './types';
// @ts-ignore
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userInfo: {
      collectionNum: undefined,
      createBy: undefined,
      createTime: undefined,
      deleteFlag: undefined,
      deliveryScore: undefined,
      descriptionScore: undefined,
      goodsNum: 0,
      id: undefined,
      memberId: undefined,
      memberName: undefined,
      merchantEuid: undefined,
      nickName: undefined,
      selfOperated: undefined,
      serviceScore: undefined,
      stockWarning: undefined,
      storeAddressDetail: undefined,
      storeAddressIdPath: undefined,
      storeAddressPath: undefined,
      storeCenter: undefined,
      storeDesc: undefined,
      storeDisable: undefined,
      storeEndTime: undefined,
      storeLogo: undefined,
      storeName: undefined,
      updateBy: undefined,
      updateTime: undefined,
      yzfMpSign: undefined,
      yzfSign: undefined,
    },
    goodsCategoryData: {
      timeStamp: 0,
      list: [],
    },
  }),
  persist: true,

  getters: {
    getGoodsCategory(state: UserState): any[] {
      return state.goodsCategoryData.list;
    },
  },

  actions: {
    // 帐号退出
    async logout() {
      await logoutUser();
      storage.clearToken();
    },
    //  获取商品分类
    async fetchGoodsCategory(state: UserState) {
      if (state.goodsCategoryData.timeStamp < new Date().getTime() / 1000) {
        const res = await getCategory();
        state.goodsCategoryData.list = res.data.result;
        state.goodsCategoryData.timeStamp = new Date().getTime() / 1000 + 600;
      }
    },
    getTongYiSystemUrl() {
      return new Promise((resolve, reject) => {
        getTongYiSystemUrl()
          .then((res) => {
            // resolve(res?.msg);
            resolve(res?.data?.result);
            // resolve('http://localhost:8001')
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export default useUserStore;
